<template>
	<view class="page-wrap" :data-theme="theme" :class="theme" :style="globalColor.style">
		<HeadCustom title="搜索地址" :isAppBtn="false"></HeadCustom>
		<SearchCustom :keyword.sync="keyword" @search="getSearch" @change="getSearch" />
		<!-- #ifdef H5 -->
		<view id="map" class="tui-maps"></view>
		<!-- #endif -->
		<!-- #ifdef MP -->
		<map class="tui-maps" id="map" :longitude="longitude" :latitude="latitude" :markers="markers"
			@tap="goMap"></map>
		<!-- #endif -->
		<view class="gps-body">
			<scroll-view class="scroll" scroll-y="true" scroll-with-animation="true"
				:style="{ height: scrollHeight + 'px' }" @scroll="scroll">
				<view class="list" v-if="surroundingPois.length > 0">
					<block v-for="(item, index) in surroundingPois" :key="index">
						<view class="address-item" @click="setAddress(item)">
							<view class="tit font30 lh44">{{ item.name }}</view>
							<view class="con color-6B707C font26 lh38">{{ item.address }}</view>
							<view class="line"></view>
						</view>
					</block>
				</view>
				<u-loadmore v-if="loading == 'loading'" fontSize="24rpx" :status="loading" />
			</scroll-view>
		</view>
	</view>
</template>

<script>
	// #ifdef H5
	import {
		jsAMap
	} from '@/static/js/jsAMap.js';
	// #endif
	// #ifdef MP
	const amapFile = require('@/static/js/amap-wx.130.js')
	// #endif
	import SearchCustom from '@/components/search/search-custom.vue';
	export default {
		components: {
			SearchCustom
		},
		data() {
			return {
				theme: getApp().globalData.appTheme,
				globalColor: getApp().globalData.globalColor,
				longitude: '',
				latitude: '',
				workAddress: '',
				workArea: '',
				ak: '20685b399d9c4b1f5e85a223a0e8d4b2',
				wchatAk: '72b8db1331fafe36487bd50770122914',
				marker: null,
				keyword: '',
				AMap: null,
				map: null,
				scrollTop: 0,
				scrollHeight: 0,
				surroundingPois: [],
				markers: [],
				myAmapFun: null,
				loading: 'none',
			};
		},
		computed: {},
		onLoad(option) {
			// uni.getSystemInfo({
			// 	success: sys => {
			// 		console.log(sys)
			// 		this.scrollHeight = sys.screenHeight - getApp().globalData.statusBarHeight - 405;
			// 	}
			// });
			// #ifdef H5
			uni.showLoading({
				title: '定位中'
			})
			if (option && option.lng) {
				this.longitude = option.lng;
				this.latitude = option.lat;
				this.getInit();
			} else {
				this.getLocation()
			}
			// #endif

			// #ifdef MP
			this.myAmapFun = new amapFile.AMapWX({ key: this.wchatAk });
			if (option && option.lng) {
				this.addMarker(option.lng, option.lat)
				this.getWchatPois(`${option.lng},${option.lat}`, (data)=>{
					uni.hideLoading()
					this.surroundingPois = data.regeocodeData.pois
				})
			} else {
				uni.showLoading({
					title: '定位中'
				})
				this.getWchatLocation()
			}
			// #endif
		},
		onReady() {
			uni.createSelectorQuery(this)
				.selectAll('.gps-body')
				.boundingClientRect(res => {
					console.log(res)
					uni.getSystemInfo({
						success: sys => {
							const {screenHeight, windowHeight} = sys
								this.scrollHeight = screenHeight - res[0].top
						}
					});
				})
				.exec();
		},
		mounted() {
			// #ifdef H5
			window.appCallback = this.appCallback;
			// #endif
		},
		methods: {
			// 获取当前定位
			getWchatLocation() {
				const that = this
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						uni.hideLoading()
						// 微信授权定位经纬度，高德API根据经纬度获得当前定位地址的相关信息
						this.addMarker(res.longitude, res.latitude)
						this.loading = 'loading'
						this.getWchatPois(res, (data)=>{
							this.loading = 'none'
							this.surroundingPois = data.regeocodeData.pois
						})
					},
				});
			},
			// 小程序点击当前地图获取相关地址
			goMap(e) {
				const dataset = e.detail
				this.loading = 'loading'
				this.addMarker(dataset.longitude, dataset.latitude)
				this.getWchatPois(dataset, (data)=>{
					this.loading = 'none'
					this.surroundingPois = data.regeocodeData.pois
				})
			},
			// 根据经纬度获取当前定位的相关信息
			getWchatPois(pois, callback) {
				let location = pois
				if(typeof(pois) == 'object'){
					location = `${pois.longitude},${pois.latitude}`
				}
				this.myAmapFun.getRegeo({
					location: location,
					success(data) {
						//打印得到所有地址信息
						if(data[0]){
							callback(data[0])
						}
					},
					fail(err) {
						console.log(err)
					}
				})
			},
			// APP 交互获取地址
			getLocation() {
				const that = this
				const data = {
					type: 'appLatLng'
				};
				this.$bridge.callHandler('recruitHandler', data, (res) => {
					console.log('recruitHandler', '返回', res)
					that.appCallback(res)
				})
				setTimeout(() => {
					if (!this.AMap) {
						uni.hideLoading()
						this.getInit()
					}
				}, 10000)
			},
			// App 交互获取地址回调
			appCallback(e) {
				if (e.lng != 0 && e.lat != 0) {
					this.longitude = e.lng;
					this.latitude = e.lat;
				}
				this.getInit();
			},
			//  H5 初始化地图
			getInit() {
				const that = this;
				jsAMap(this.ak).then(AMap => {
					this.AMap = AMap;
					let config = {
						resizeEnable: true,
						zoom: 16
						// mapStyle: "amap://styles/dark"
					};
					if (that.latitude) {
						config.center = [that.longitude, that.latitude];
					}
					let map = new AMap.Map('map', config);
					uni.hideLoading()
					this.map = map;
					// map.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Geolocation', 'AMap.Geocoder']);
					if (!that.latitude) {
						map.plugin('AMap.Geolocation', () => {
							var geolocation = new AMap.Geolocation({
								enableHighAccuracy: true, //是否使用高精度定位，默认:true
								timeout: 10000, //超过10秒后停止定位，默认：无穷大
								maximumAge: 0, //定位结果缓存0毫秒，默认：0
								convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
								showButton: true, //显示定位按钮，默认：true
								buttonPosition: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
								buttonOffset: new AMap.Pixel(10, 20),
								showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
								showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
								panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
								zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
							});
							map.addControl(geolocation);
							geolocation.getCurrentPosition((s, r) => {
								console.log('s====================>', s);
								let address_now = {}
								if (s == 'complete') {
									console.log('成功定位信息', r);
									address_now.lng = r.position.lng
									address_now.lat = r.position.lat
								} else {
									console.log('失败定位信息', r);
									address_now = map.getCenter()
								}
								that.mapAddress(address_now.lng, address_now.lat)
								that.addMarker(address_now.lng, address_now.lat)
							});
						});
					} else {
						that.mapAddress(that.longitude, that.latitude);
						that.addMarker(that.longitude, that.latitude);
					}
					map.on('click', function(e) {
						that.longitude = e.lnglat.lng;
						that.latitude = e.lnglat.lat;
						that.scrollTop = 0;
						that.surroundingPois = []
						that.mapAddress(e.lnglat.lng, e.lnglat.lat);
						that.addMarker(e.lnglat.lng, e.lnglat.lat);
					});
					map.on('zoomstart', function(e) {
						console.log('zoomstart', e);
					});
					map.on('zoomchange', function(e) {
						console.log('zoomchange', e);
					});
					map.on('zoomend', function(e) {
						console.log('zoomend', e);
					});
				});
			},
			// 搜索地址
			getSearch() {
				// #ifdef H5
				const that = this;
				const AMap = this.AMap;
				const map = this.map;
				this.loading = 'loading'
				// 实例化Autocomplete
				map.plugin(['AMap.Autocomplete'], () => {
					var autoComplete = new AMap.Autocomplete({
						city: '全国'
					});
					if(that.keyword){
						autoComplete.search(that.keyword, function(status, result) {
							console.log('Autocomplete', status, result);
							that.loading = 'none'
							if (status === 'complete' && result.info == 'OK') {
								let tipsList = []
								result.tips.filter(item=>{
									if(item.location){
										tipsList.push(item)
									}
								})
								that.workArea = tipsList[0].district;
								that.addMarker(tipsList[0].location.lng, tipsList[0].location.lat);
								that.surroundingPois = tipsList;
							}else{
								that.surroundingPois = []
								uni.showToast({
									icon: 'none',
									title: '抱歉，未找到结果'
								})
							}
						});
					}else{
						that.surroundingPois = []
						that.loading = 'none'
					}
				});
				// #endif
				// #ifdef MP
				this.getWchatSearch(this.keyword)
				// #endif
			},
			// 小程序搜索
			getWchatSearch(keywords) {
				var that = this;
				that.surroundingPois = []
				if(keywords){
					this.loading = 'loading'
					that.myAmapFun.getInputtips({
						keywords: keywords,
						// location: poisData[0].location,
						city: '全国',
						// city: poisData[0].cityname || '',
						success: function(data) {
							console.log('getInputtips', data)
							that.loading = 'none'
							if (data && data.tips) {
								// 过滤没有经纬度的地址
								let tipsList = []
								data.tips.filter(item=>{
									if(item.location && item.location.length>0){
										tipsList.push(item)
									}
								})
								const location = tipsList[0].location.split(",")
								that.addMarker(location[0], location[1])
								that.surroundingPois = tipsList
							}
						},
						fail() {
							that.loading = 'none'
							uni.showToast({
								icon: 'none',
								title: '抱歉，未找到结果'
							})
						}
					})
				}
			},
			// H5 根据经纬度获取当前地图地址
			mapAddress(lng, lat) {
				const that = this;
				const AMap = this.AMap;
				const map = this.map;
				let position = [lng, lat];
				map.plugin(['AMap.PlaceSearch', 'AMap.Geocoder'], () => {
					var geocoder = new AMap.Geocoder();
					var placeSearch = new AMap.PlaceSearch({
						city: '全国'
					});
					geocoder.getAddress(position, (status, result) => {
						console.log('Geocoder', result);
						that.workArea = result.regeocode.addressComponent.district;
						if (status === 'complete' && result.info === 'OK') {
							placeSearch.search(result.regeocode.formattedAddress, function(status,
								result) {
								// 搜索成功时，result即是对应的匹配数据
								console.log('PlaceSearch', status, result);
								if (result.info == 'OK') {
									that.surroundingPois = result.poiList.pois;
								}
							});
						}
					});
				});
			},
			// 根据经纬度标记
			addMarker(lng, lat) {
				console.log('标注', lng, lat);
				const that = this;
				// #ifdef H5
				const AMap = this.AMap;
				const map = this.map;
				if (this.marker) {
					map.remove(this.marker);
				}
				map.setCenter([lng, lat]);
				const marker = new AMap.Marker({
					icon: new AMap.Icon({
						image: 'https://ebc-prod.cdn.benwunet.com/uni-static/location.png',
						size: new AMap.Size(28, 28), //图标所处区域大小
						imageSize: new AMap.Size(28, 28) //图标大小
					}),
					position: [lng, lat],
					offset: new AMap.Pixel(-13, -30)
				});
				this.marker = marker;
				map.add(marker);
				// #endif
				// #ifdef MP
				that.latitude = lat
				that.longitude = lng
				that.markers = [{
					id: 1111111, //标记点 id
					width: 20,
					height: 20,
					longitude: lng,
					latitude: lat,
					iconPath: 'https://ebc-prod.cdn.benwunet.com/uni-static/location.png'
				}]
				// #endif

			},
			// 设置地址
			setAddress(res) {
				console.log(res)
				// #ifdef H5
				const that = this;
				const AMap = this.AMap;
				const map = this.map;
				let position = [res.location.lng, res.location.lat];
				map.plugin(['AMap.Geocoder'], () => {
					var geocoder = new AMap.Geocoder();
					geocoder.getAddress(position, (status, result) => {
						result.location = res.location
						that.setRecruitment(result)
					});
				});
				// #endif
				// #ifdef MP
				// 根据定位获取 地址称
				this.getWchatPois(res.location, (data)=>{
					this.setRecruitment(data)
				})
				// #endif
			},
			// 设置职位地址并且返回
			setRecruitment(data){
				console.log(data)
				const recruitmentTemp = getApp().globalData.recruitmentTemp;
				// #ifdef H5
				const { regeocode: { formattedAddress, addressComponent: { city, province, district } } } = data;
				recruitmentTemp.workAddress = formattedAddress;
				recruitmentTemp.latitude = data.location.lat;
				recruitmentTemp.longitude = data.location.lng;
				recruitmentTemp.cityName = city ? city : -1;
				// #endif
				// #ifdef MP
				const { regeocodeData: { formatted_address, addressComponent: { city, province, district } } } = data;
				recruitmentTemp.workAddress = formatted_address;
				recruitmentTemp.latitude = data.latitude;
				recruitmentTemp.longitude = data.longitude;
				recruitmentTemp.cityName = city[0] ? city[0] : -1;
				// #endif
				recruitmentTemp.workArea = `${city} ${province} ${district}`;
				recruitmentTemp.provinceName = province;
				recruitmentTemp.districtName = district;
				uni.navigateBack({ delta: 1 });
			},
			scroll(e) {
				// this.scrollTop = e.detail.scrollTop;
			}
		}
	};
</script>

<style scoped lang="scss">
	.page-wrap {
		min-height: calc(100vh);
	}

	.address-item {
		padding: 0 40rpx;
	}

	.list {
		padding: 40rpx 0 0;
	}

	.line {
		margin: 32rpx 0;
		height: 1rpx;
		background: var(--backgroundDivisionColor);
	}

	.tui-maps {
		width: 750rpx;
		height: 600rpx;
		// position: relative;
	}
</style>